<script setup lang="ts">
import { useApi } from "@/views/domain/knowledge/api/ollama";
import { ref } from "vue";
import { db, PullingModels } from "@/views/domain/knowledge/store/database";
import { ElMessage } from "element-plus";
const emit = defineEmits(["refresh"]);
const { pullModel } = useApi();
const pulling = ref(false);
const show = ref(false);
const modelName = ref("");

const doPullModel = local => {
  pulling.value = true;
  pullModel({ name: modelName.value })
    .then(res => {
      show.value = false;
      if (res.total > 0) {
        ElMessage.success(`${modelName.value} 模型拉取成功`);
        db.models.update(local, { status: "success" });
      } else {
        db.models.update(local, { status: "fail" });
        ElMessage.error(`${modelName.value} 模型拉取失败`);
      }
    })
    .finally(() => {
      pulling.value = false;
      show.value = false;
    });
  emit("refresh");
};

const onSubmit = async () => {
  // 验证本地是否正在拉取中
  var local: PullingModels = {
    name: modelName.value,
    status: "pulling",
    createdAt: new Date()
  };
  try {
    const local = await findIsModelPulling(modelName.value);
    if (local && local.status === "pulling") {
      ElMessage.error(`${modelName.value} 模型正在拉取中`);
      return;
    } else if (local && local.status === "success") {
      ElMessage.error(`${modelName.value} 模型已经拉取成功`);
      return;
    } else {
      db.models.add(local);
    }
  } catch (e) {
    db.models.add(local);
  }
  doPullModel(local);
};

const findIsModelPulling = (model: string) => {
  return db.models.where("name").equals(model)?.limit(1)?.first();
};

const jumpToOllama = () => {
  window.open("https://ollama.com/search", "_blank");
};

defineExpose({
  show: () => {
    show.value = true;
  }
});
</script>

<template>
  <el-dialog v-model="show" v-loading="pulling" title="拉取模型" width="50%">
    <el-form label-position="top">
      <el-form-item label="模型名称">
        <el-alert type="info" show-icon :closable="false">
          模型名称格式为：name:version, 如: "deepseek-r1:32b"
        </el-alert>
        <el-input v-model="modelName" placeholder="name:version" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div class="dialog-footer">
        <el-button text type="danger" @click="jumpToOllama()"
          >模型列表</el-button
        >
        <el-button @click="show = false">Cancel</el-button>
        <el-button type="primary" @click="onSubmit()">OK</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
